package com.ktjiaotu.examples;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Author: DABINGCHNEGJIAO
 * @CreateTime: 2025-06-04
 * @Description:
 * @Version: 1.0
 */
public class SimpleBeanConvertor {
    private static Logger logger = Logger.getLogger(SimpleBeanConvertor.class);

    public static <T> T convert(HttpServletRequest request, Class<T> targetType) throws InstantiationException, IllegalAccessException, InvocationTargetException, ParseException {

        //获取所有请求参数
        Map<String, String[]> params = request.getParameterMap();
        if (params == null || params.isEmpty()) {
            return null;
        }
        T t = targetType.newInstance();
        Method[] methods = targetType.getMethods();
        if (methods != null && methods.length > 0) {
            for (Method method : methods) {
                //仅处理setter
                if (method.getName().startsWith("set")) {
                    //获取参数列表
                    Class[] args = method.getParameterTypes();
                    if (args.length == 1) {  //仅处理一个参数的setter
                        String paramName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
                        if (params.containsKey(paramName)) {
                            try {
                                Object value = parseValue(params.get(paramName), args[0]);
                                method.invoke(t, value);
                            } catch (ParseException e) {
                                logger.debug("参数转换异常", e);
                                e.printStackTrace();
                                throw e;
                            } catch (UnsupportedTypeException e) {
                                throw new RuntimeException(e);
                            }
                        } else if (Boolean.class == args[0] || boolean.class == args[0]) {
                            method.invoke(t, false);
                        }
                    }
                }
            }
        }
        return t;
    }

    private static Object parseValue(String[] values, Class type) throws ParseException, UnsupportedTypeException {
        if (String.class == type) {
            return values[0];
        }
        if (Date.class == type) {
            return new SimpleDateFormat("yyyy-MM-dd ").parse(values[0]);
        }
        if(char.class == type || Character.class == type){
            return values[0].charAt(0);
        }
        if (Integer.class == type || int.class == type) {
            return Integer.valueOf(values[0]);
        }
        if (short.class==type || byte.class == type || long.class== type ||float.class == type || double.class == type) {
            try {
                //将值类型变为对应的包装类型
                type =Class.forName("java.lang"+type.getName().substring(0,1).toUpperCase()+type.getName().substring(1));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (type.getName().startsWith("java.lang." )|| type.getName().startsWith("java.math.")){
                try {
                    return  type.getConstructor(String.class).newInstance(values[0]);
                }catch (Exception e){
                    throw new UnsupportedTypeException();
                }
            }
        }
        return values[0];
    }
}
